import Vue from 'vue'
import axios from 'axios'

const service = axios.create({
  baseURL: '',
  timeout: 5000,
  responseType: 'json',
  withCredentials: false // cookie 表示跨域请求时是否需要使用凭证
})

service.interceptors.request.use(
  config => {
    // let token = vm.$store.getters.getToken;
    !config.data && (config.data = {}) // 设置默认 data
    // token && (config.data.token = token);
    if (!config.headers['Content-Type']) { // 设置默认响应头
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      if (Object.prototype.toString.call(config.data) != '[object FormData]') {
        // config.data = qs.stringify(config.data)
      }
    }
    // config.method === 'OPTIONS'
    return config
  },
  error => {
    // Toast({
    //   message: error,
    //   position: 'top',
    //   duration: 1000
    // })
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    /* // IE 9
    if (response.data == null && response.config.responseType === 'JSON' && response.request.responseText != null) {
      try {
        response.data = JSON.parse(response.request.responseText);
      } catch (e) {
      }
    }
    return response; */

    if (response.status === 200) {
      const data = response.data || JSON.parse(response.request.responseText)
      const stateCode = data.errorCode
      if (data == '') {
        Toast({
          message: vm.$i18n.locale == 'English' ? 'The data fluctuated greatly and did not conform to the statistical law' : '数据波动较大，不符合统计学规律',
          position: 'bottom',
          duration: 2000
        })
      }
      if (stateCode == null) {
        return data
      }
      let res
      switch (stateCode) {
        case 0:
          res = data
          return data
          break
        default:
          res = data
      }
      res = data
      return Promise.reject(res)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    if ((error + '').indexOf('timeout') != -1) {
      Toast({
        message: 'Request timeout',
        position: 'bottom',
        duration: 2000
      })
    }
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          Toast({
            message: 'Server repair in progress...',
            position: 'top',
            duration: 2000
          })
          break
        // 404请求不存在
        case 404:
          Toast({
            message: 'Network request does not exist',
            position: 'top',
            duration: 1000
          })
          break
        // 其他错误，直接抛出错误提示
        default:
          Toast({
            message: error.response.data.message,
            position: 'top',
            duration: 1500
          })
      }
      return Promise.reject(error.response)
    }
  }
)

Vue.prototype.$http = service

export default service

